package com.fadadianqi.logistics.admin.plugins.gree;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.Constants;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.commons.ParamHelper;
import com.fadadianqi.logistics.customer.model.Customer;
import com.fadadianqi.logistics.customer.model.Town;
import com.fadadianqi.logistics.customer.model.Village;
import com.fadadianqi.logistics.customer.service.CustomerService;
import com.fadadianqi.goods.model.Goods;
import com.fadadianqi.goods.service.GoodsService;
import com.fadadianqi.logistics.sell.model.Bill;
import com.fadadianqi.logistics.sell.service.BillService;
import com.yeqiangwei.commons.io.FileHelper;
import com.yeqiangwei.commons.util.DateTimeUtils;
import com.yeqiangwei.commons.util.StringHelper;
import com.yeqiangwei.commons.util.Utils;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.mortbay.log.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 格力空调安装卡打印
 *
 * @author aroot
 */
@Controller
public class GreeInstallCardController {

    /**
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/a/ajax/plugins/gree/installForm", method = RequestMethod.GET)
    public String showForm(HttpServletRequest request, ModelMap modelMap) {
        String billId = ParamHelper.getBillId(request, null);
        String goodsId = ParamHelper.getGoodsId(request, null);
        Bill bill = billService.getById(billId);
        Goods goods = goodsService.getGoodsById(goodsId);
        Customer customer = customerService.getById(bill.getCustomerId());

        InstallCard card = null;
        String tmpJSON = getTmpInstallCard();
        if (tmpJSON == null) {
            card = new InstallCard();
            card.setBuyDate(fmtDateTime(bill.getAddTime()));
            card.setInstallDate(fmtDateTime(bill.getAddTime()));
        } else {
            card = (InstallCard) JSONProvider.toBean(tmpJSON, InstallCard.class);
            card.setInnerCode(StringHelper.EMPTY);
            card.setOuterCode(StringHelper.EMPTY);
        }
        if (customer != null) {
            Town town = customerService.getTownById(customer.getTownId());
            Village village = customerService.getVillageById(customer.getVillageId());
            if (town != null && village != null) {
                String address = town.getName() + village.getName() + bill.getMemo();
                card.setAddress(address);
            }
            card.setCustomerName(customer.getName());
            if (ValidatorHelper.isNotEmpty(customer.getTel())) {
                card.setTel(customer.getTel());
            } else if (ValidatorHelper.isNotEmpty(customer.getMobile())) {
                card.setTel(customer.getMobile());
            }
        }
        card.setGoodsName(goods.getName());
        card.setReceiptCode(String.valueOf(Utils.getRandomNumber(198202, 999999)));
        modelMap.put("command", card);
        modelMap.put("bill", bill);
        return "/admin/plugins/gree/installForm";
    }

    private String fmtDateTime(Date d) {
        if (d == null) {
            return null;
        }
        return DateTimeUtils.format(d.getTime(), DateTimeUtils.FMT_YYYY_MM_DD);
    }

    /**
     * @param form
     * @param result
     * @param status
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/a/plugins/gree/installCard/print", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> doPrint(
            @ModelAttribute("command") InstallCard form, BindingResult result,
            SessionStatus status) throws IOException {
        AjaxResult rs = null;
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");

        PrintInstallCardService pics = new PrintInstallCardService(form);
        try {
            pics.doPrint();
            rs = new AjaxResult(form, Boolean.TRUE, null);
        } catch (Exception e) {
            rs = new AjaxResult(form, Boolean.FALSE, null);
        }
        // 缓存这次打印的安装卡到硬盘
        String buf = JSONProvider.toJSON(form);
        String path = tmpFilePath();
        FileHelper.initpath(path);
        FileHelper.createFile(path + tmpFileName(), buf, Constants.UTF_8, true);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.CREATED);
    }

    public String getTmpInstallCard() {
        String path = tmpFilePath() + tmpFileName();
        Log.debug("#getTmpInstallCard# " + path);
        try {
            File file = new File(path);
            if (file.exists()) {
                return FileHelper.readText(file, Constants.UTF_8);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String tmpFilePath() {
        String baseDir = System.getProperty("base.dir", "..");
        String path = baseDir + "tmp" + FileHelper.separator;
        return path;
    }

    private String tmpFileName() {
        return "install.tmp";
    }

    @Autowired
    private BillService billService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private GoodsService goodsService;

}
